package com.corticon.dialogs.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.validation.Errors;

/**
 *
 * @author Lifan Yang
 * @since 2008-12-18
 */
public class ValidationUtils {

    /**
     * The method is used to validate the simple string like a name. The numbers and alphabets and
     * '_' are valid.
     *
     * @param errors
     * @param validateString
     * @param field
     * @param messageCode
     */
    public static void simpleStringValidate(Errors errors, String validateString, String field,
        String messageCode) {
        List<Character> excludedChars = new ArrayList<Character>();
        excludedChars.add('_');
        commonCharactersValidate(validateString, excludedChars, errors, field, messageCode, null,
            "default message");
    }

    public static void commonCharactersValidate(String characters, List<Character> excludedChars,
        Errors errors, String fieldName, String errorCode, Object[] errorArgs, String defaultMessage) {

        boolean isValid = true;

        if (isValid) {
            isValid =
                checkInvalidCharacters(characters, ' ', '/', excludedChars) && checkInvalidCharacters(
                characters, ':', '@', excludedChars) && checkInvalidCharacters(characters, '[', '`',
                excludedChars) && checkInvalidCharacters(characters, '{', '~', excludedChars);
        }

        // If the password is invalid, add the error message.
        if (!isValid) {
            errors.rejectValue(fieldName, errorCode, errorArgs, defaultMessage);
        }
    }

    public static boolean checkValidCharacters(String value, char asciiBegin, char asciiEnd,
        List<Character> excludedChars) {
        boolean isValidPassword = false;

        int i = asciiBegin;

        while (!isValidPassword) {

            if (excludedChars != null && excludedChars.contains((char) i)) {
                i++;
                continue;
            }

            isValidPassword = value.indexOf((char) i) > -1 ? true : false;

            i++;
            if (i > asciiEnd) {
                break;
            }
        }

        return isValidPassword;
    }

    public static boolean checkInvalidCharacters(String value, char asciiBegin, char asciiEnd,
        List<Character> excludedChars) {
        boolean isValidPassword = true;

        int i = asciiBegin;

        while (isValidPassword) {

            if (excludedChars != null && excludedChars.contains((char) i)) {
                i++;
                continue;
            }

            isValidPassword = value.indexOf((char) i) > -1 ? false : true;

            i++;
            if (i > asciiEnd) {
                break;
            }
        }

        return isValidPassword;
    }
}
